package com.cedifie.lendapp.ui.loan.fm

import android.app.Activity
import android.content.Intent
import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import androidx.activity.result.ActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import com.cedifie.lendapp.R
import com.cedifie.lendapp.databinding.FmLoanLimitBinding
import com.cedifie.lendapp.http.HttpHelper
import com.cedifie.lendapp.mvp.MvpFm
import com.cedifie.lendapp.ui.loan.act.CedLoanApplyAct
import com.cedifie.lendapp.ui.loan.impl.CedLoanLimitPresenterImpl
import com.cedifie.lendapp.ui.loan.view.ICedLoanLimitView
import com.cedifie.lendapp.ui.steps.act.CedStepAct
import com.cedifie.lendapp.ui.user.act.CedPermissionReasonAct
import com.cedifie.lendapp.utils.event.CedEventManager
import com.cedifie.lendapp.utils.event.CedEventType
import com.cedifie.lendapp.utils.helper.SharedHelper
import com.cedifie.lib_permission.OnPermissionCallback
import com.cedifie.lib_permission.XXPermissions
import org.greenrobot.eventbus.EventBus
import org.json.JSONObject

/**
 * Cedifie
 * @Author wwdeng
 * @CreateTime: 2024/6/17 13:41
 * @Annotation：贷款额度Page
 */
class CedLoanLimitFm(): MvpFm<ICedLoanLimitView, CedLoanLimitPresenterImpl>(),ICedLoanLimitView {
    private var _binding: FmLoanLimitBinding? = null
    private val binding get() = _binding ?: throw IllegalStateException(
        "binding is null"
    )

    var isComplete = false
    constructor(isComplete: Boolean): this(){
        this.isComplete = isComplete
    }

    override fun getCedRootView(inflater: LayoutInflater): View {
        _binding = FmLoanLimitBinding.inflate(inflater)
        return binding.root
    }

    override fun initCedView() {
        rootViewBinding.containerLayout.setBackgroundColor(Color.parseColor("#00000000"))
        initCedRefreshLayout()
    }

    override fun initCedListener() {
        //完善流程、申请贷款
        _binding?.btnApply?.setOnClickListener {
            if (isComplete){//申请贷款
                HttpHelper.addCedEventAction(CedEventType.CLICK.CED_CLICK_LOAN_LIMIT_APPLY,"")
            } else {//完善资料
                HttpHelper.addCedEventAction(CedEventType.CLICK.CED_CLICK_LOAN_LIMIT_ADD_INFORMATION,"")
            }
            //立即上报埋点
            CedEventManager.getInstance().updateCedEventsNow()
            mvpPresenter?.checkCedAllPermissionsAgree()
        }
    }

    override fun initCedData() {
        HttpHelper.addCedEventAction(CedEventType.PAGE.CED_PAGE_LOAN_LIMIT_START,"")
        showCedStateView()
    }

    override fun createMvpPresenter(): CedLoanLimitPresenterImpl {
        return CedLoanLimitPresenterImpl(context)
    }

    /**
     * 权限声明列表
     */
    private val permissionReasonResultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult ->
        when (result.resultCode) {
            Activity.RESULT_OK -> {
                var isNext = false
                result.data?.let { bundle ->
                    val isAgree = bundle.getBooleanExtra("isPermissionAgree",false)
                    //同意，校验权限 进行下一步
                    isNext = if (isAgree){
                        true
                    } else {//拒绝，
                        //是否是广告渠道
                        val isAdSource = SharedHelper.getCedSPBoolean(SharedHelper.CED_SPKEY.CEDIFIE_IS_ADSOURCE)
                        //非广告渠道才继续校验进行下一步
                        !isAdSource
                    }
                }
                if (isNext){
                    mvpPresenter?.checkCedAllPermissionsAgree()
                }
            }
        }
    }

    /* 初始化刷新 */
    private fun initCedRefreshLayout() {
        //禁止加载
        _binding?.refreshLayout?.setEnableLoadMore(false)
        _binding?.refreshLayout?.setEnableAutoLoadMore(false)
        _binding?.refreshLayout?.setOnRefreshListener {
            //发送刷新流程通知
            EventBus.getDefault().post(CedEventType.NOTICE.CED_PROCESS_REFRESH)
        }
        _binding?.refreshLayout?.setOnLoadMoreListener {
            _binding?.refreshLayout?.finishLoadMore()
        }
    }

    /**
     * 显示样式
     */
    fun showCedStateView(){
        mvpPresenter?.loadCedLoanLimitAction()
        when(isComplete){
            true -> {//已完成 - 显示额度
                _binding?.congratulationsLayout?.visibility = View.VISIBLE
                _binding?.limitApplyTips?.visibility = View.VISIBLE
                _binding?.btnApply?.text = getString(R.string.btn_apply)
                _binding?.stepLayout?.visibility = View.GONE
            }
            else -> {//未完成 - 显示完善资料
                _binding?.congratulationsLayout?.visibility = View.GONE
                _binding?.limitApplyTips?.visibility = View.GONE
                _binding?.btnApply?.text = getString(R.string.btn_process_next)
                _binding?.stepLayout?.visibility = View.VISIBLE
            }
        }
    }

    /**
     * 显示额度信息
     */
    override fun showCedLoanLimitData(data: JSONObject) {
        //不显示百分比
        _binding?.circleSeekBar?.setShowPercentText(false)
        var progressAmount = 0
        when(isComplete){
            true -> { //已完成
                val showAmount = data.optString("amount")
                progressAmount = showAmount.toInt()
                _binding?.circleSeekBar?.max = progressAmount
                _binding?.circleSeekBar?.labelText = showAmount
            }
            else -> {//未完成
                progressAmount = data.optString("amount2").toInt()
                _binding?.circleSeekBar?.max = data.optString("amount1").toInt()
                _binding?.circleSeekBar?.labelText = progressAmount.toString()

                //登录额度
                _binding?.textLoginAmount?.text = String.format(getString(R.string.loan_limit_amount),data.optString("amount2"))
                //流程完成额度
                _binding?.textCompletedAmount?.text = String.format(getString(R.string.loan_limit_amount),data.optString("amount3"))
            }
        }
        //设置额度
        _binding?.circleSeekBar?.showAnimation(0, progressAmount, 1500)
    }

    /**
     * 权限申请dialog
     */
    override fun showCedPermissionReason() {
        val intent = Intent(context, CedPermissionReasonAct::class.java)
        permissionReasonResultLauncher.launch(intent)
    }

    /**
     * 授权
     */
    private fun requestCedPermission(data: JSONObject){
        val permission = data.optString("permission")
        XXPermissions.with(requireContext())
            // 申请多个权限
            .permission(permission)
            .request(object: OnPermissionCallback {
                override fun onGranted(permissions: MutableList<String>, p1: Boolean) {
                    if (p1){
                        var permissionString = ""
                        permissions.forEach {
                            permissionString = "$permissionString$it,"
                        }
                        HttpHelper.addCedEventAction(CedEventType.CLICK.CED_CLICK_PERMISSION_SYSTEM_AGREE,permissionString.substring(0,permissionString.length - 1))
                        mvpPresenter?.checkCedAllPermissionsAgree()
                    }
                }
                override fun onDenied(permissions: MutableList<String>, doNotAskAgain: Boolean) {
                    var permissionString = ""
                    permissions.forEach {
                        permissionString = "$permissionString$it,"
                    }
                    HttpHelper.addCedEventAction(CedEventType.CLICK.CED_CLICK_PERMISSION_SYSTEM_DENY,permissionString.substring(0,permissionString.length - 1))
                    XXPermissions.startPermissionActivity(requireContext(),permission)
                }
            })
    }

    /**
     * 权限校验完成
     */
    override fun showCedPermissionCheckSuccess() {
        when(isComplete){
            true -> {//申贷
                showCedLoanApplyPage()
            }
            else -> {//显示完善流程页面
                showCedProcessStepPage()
            }
        }
    }

    /**
     * 显示申请贷款页面
     */
    private fun showCedLoanApplyPage() {
        onIntent(CedLoanApplyAct::class.java)
    }

    /**
     * 显示完善流程页面
     */
    private fun showCedProcessStepPage() {
        onIntent(CedStepAct::class.java)
    }

    override fun hideCedLoading() {
        super.hideCedLoading()
        _binding?.refreshLayout?.finishRefresh()
    }

    override fun onDestroy() {
        super.onDestroy()
        HttpHelper.addCedEventAction(CedEventType.PAGE.CED_PAGE_LOAN_LIMIT_END,"")
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

}